package jobs;

import java.io.File;
import java.io.FilenameFilter;

import play.Logger;
import play.Play;
import play.cache.Cache;
import play.jobs.Every;
import play.jobs.Job;
import controllers.NzbGrabber;

@Every("10s")
public class CheckNewNzbFiles extends Job {
	
	public File				nzbDirectory;
	public File[]			nzbFilesList;
	public File				currentFile;
	public DownloadStatus	downloadStatus;
	
	public final static String NZB_DIRECTORY = Play.configuration.get("nzb_files_directory").toString();
	public final static Integer NB_DOWNLOAD_THREAD = Integer.parseInt(Play.configuration.get("download_threads").toString());
	public CheckNewNzbFiles()
	{
		nzbDirectory = new File(NZB_DIRECTORY);
	}
	
	public void doJob()
	{
		scanNzbDirectory();

		if (nzbFilesList.length > 0) {
			for(Integer currentIndex = 0; currentIndex < nzbFilesList.length; currentIndex++) {
				try {
					currentFile = nzbFilesList[currentIndex];
					downloadStatus = new DownloadStatus(0, 0, 0, 0, "", "", "");
					Cache.set("DOWNLOAD_STATUS", downloadStatus);
					handleNzb(currentFile);
					currentFile.delete();
				} catch (Exception e) {
					Logger.error("Erreur lors du telechargement du fichier : " + currentFile.getName());
					e.printStackTrace();
				}
			}
		}
	}
	
	public void scanNzbDirectory()
	{
		FilenameFilter nzbFileNameFilter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".nzb");
			}
		};
		this.nzbFilesList = nzbDirectory.listFiles(nzbFileNameFilter);
		if (this.nzbFilesList.length > 0) {
			System.out.println("Fichier(s) Nzb trouve(s).");
		} else {
			System.out.println("Aucun Fichier Nzb trouve");
		}
	}
	
	public void handleNzb(File nzbFile) throws Exception
	{
		NzbGrabber grabber = new NzbGrabber(nzbFile, NB_DOWNLOAD_THREAD);
		grabber.start();
	}
}
